package com.zang.blogz.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zang.blogz.constant.AuthorConstant;
import com.zang.blogz.constant.ResultConstant;
import com.zang.blogz.entity.OperationLog;
import com.zang.blogz.mapper.OperationLogMapper;
import com.zang.blogz.model.output.admin.AdminOperationLogVO;
import com.zang.blogz.result.Result;
import com.zang.blogz.service.OperationLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.github.vampireachao.stream.core.optional.Opp;
import io.github.vampireachao.stream.plugin.mybatisplus.Database;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 朵橙i
 * @since 2022-06-17
 */
@Service
public class OperationLogServiceImpl extends ServiceImpl<OperationLogMapper, OperationLog> implements OperationLogService {

    @Override
    public IPage<AdminOperationLogVO> pageResult(String moduleName, Page<OperationLog> page) {


        IPage<OperationLog> logPage = Database.page(page, Wrappers.lambdaQuery(OperationLog.class)
                .like(Opp.ofStr(moduleName).isPresent(), OperationLog::getOptModule, moduleName));

        String name = (String) StpUtil.getExtra("name");

        return logPage.convert(result -> {
            AdminOperationLogVO vo = new AdminOperationLogVO();
            vo.setCanDelete(AuthorConstant.authorSet.contains(name));
            BeanUtil.copyProperties(result, vo);
            return vo;
        });
    }

    @Override
    public Result<String> deleteByLogId(Integer logId) {

        String name = (String) StpUtil.getExtra("name");

        boolean contains = AuthorConstant.authorSet.contains(name);
        if (!contains) {
            return Result.error("抱歉您不是博客作者不可以删除日志");
        }

        removeById(logId);

        return Result.ok(ResultConstant.DELETE_SUCCESS);
    }
}
